/**
 * Created by yezq on 2017/5/26.
 */
var express    = require('express') //加载模块
var app        = express() //实例化之
var bodyParser = require('body-parser')
var http       = require('http')
var fs         = require('fs')
const iconv    = require('iconv-lite')
var util       = require('util')
var cheerio    = require('cheerio')
var xml2js     = require('xml2js')
var j2x = new xml2js.Builder();  // JSON->xml
var x2j = new xml2js.Parser();   //xml -> json
var map = {
  "1": {
    id:   1,
    name: "test1"
  },
  "2": {
    id:   2,
    name: "test2"
  }
} //定义一个集合资源，key为字符串完全是模仿java MAP<T,E>，否则谁会这么去写个hash啊！
//var restApi = require('./rest-client')
app.set('json spaces', 2)
app.disable('x-powered-by')
app.disable('etag')
app.all('*', function(req, res, next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("X-Powered-By", 'yeernet-engine')
  res.header("Content-Type", "application/json;charset=utf-8");
  res.header("Encodeing", "utf8");
  res.header("server", "nginx");
  next();
});
var str = `
<style>td{padding:10px}</style>
<table>
<tr><td>name</td><td>url</td><td>desc</td></tr>
<tr><td>bnsRole</td><td>bns/role/:serverId/:id</td><td>/</td></tr>
</table>
`
app.get('/', function(req, res){ //Restful Get方法,查找整个集合资源
  res.set({
    'Content-Type': 'text/html',
    'Encodeing':    'utf8'
  });
  res.send(str)
})


app.all('/consultings/haodf/:catalogryId/:page', function(req, res){
  var catalogryId = req.params.catalogryId
  var page       = req.params.page
  //res.send({
  //    headers: req.headers,
  //    method: req.method,
  //    url: req.url,
  //    body: req.body,
  //    params: req.params,
  //    query: req.query
  //})
  var content = '';
  var options = {
    host:    'query.yahooapis.com',
    port:    80,
    path:    "/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%27http%3A%2F%2Fzixun.haodf.com%2Fdispatched%2F"
    +catalogryId+".htm%3Fp%3D"+page+"%26t%3D"+/*new Date().getTime()+*/
    "%27%20and%20xpath%3D%27%2F%2Ful%5B%40class%3D%22pt5%20izixun-newZixunList%22%5D%27&format=json&diagnostics=true",
    method:  'GET'
  }
  // options.headers['content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  // options.headers['content-Length'] = args.data.length
  //res.writeHead(200, {
  //  'Content-Type': 'text/html'
  //});
  var req = http.request(options, function(res2){
    util.log( '['+options.method+'] http://'+options.host+options.path)
    util.log('STATUS: ' + res2.statusCode);
    util.log('HEADERS: ' + util.inspect(res2.headers));
    util.log('HEADERS.date: ' + util.inspect(res2.headers.date));
    //res2.setEncoding('utf8');
    res2.on('data', function(body){
      content += body;
    }).on("end", function(){
      //res.write(content);
      writeFile('./log/' + new Date().toLocaleDateString() + '-' + new Date().getHours() + '-' + new Date().getMinutes() + '-' + new Date().getSeconds() + '-res.txt', content.toString())
      //content = hexToDec(content)
      console.log( typeof (content))
      content = JSON.parse(content)
      //res.header('content-type', 'text/html')
      res.send(content/*.query.results.ul.li*/)
    })
  }).on('error', function(e){
    console.log("Request Error: " + e.message)
  })
  //req.write('\n')
  console.log(req.output + '\n')
  req.end()
})


app.all('/consulting/haodf/:url', function(req, res){
  var url = req.params.url
  console.log(url)
  //res.send({
  //    headers: req.headers,
  //    method: req.method,
  //    url: req.url,
  //    body: req.body,
  //    params: req.params,
  //    query: req.query
  //})
  var content = ''
  var htmlData = ''
  var options = {
    host:    'query.yahooapis.com',
    port:    80,
    path:    '/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%27'+url+
    '%27and%20xpath%3D%27%2F%2Fdiv%5B%40class%3D"zzx_yh_stream"%5D%2F%2Fdiv%5B%40class%3D"stream_yh_right"%5D%2F%2Fdiv%5B%40class%3D"h_s_info_cons"%5D%27&format=json&diagnostics=true',
    method:  'GET'
  }
  // options.headers['content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  // options.headers['content-Length'] = args.data.length
  //res.writeHead(200, {
  //  'Content-Type': 'text/html'
  //});
  var req = http.request(options, function(res2){
    util.log( '['+options.method+'] http://'+options.host+options.path)
    util.log('STATUS: ' + res2.statusCode)
    util.log('HEADERS: ' + util.inspect(res2.headers))
    util.log('HEADERS.date: ' + util.inspect(res2.headers.date))
    //res2.setEncoding('utf8');
    res2.on('data', function(body){
      content += body
      //content += iconv.decode(body, 'gbk')
    }).on("end", function(){
      //res.write(content);
      //var $ = cheerio.load(content)
      //var consult = $('.zzx_yh_stream').html().toString()
      //console.log( consult )
      //var json = x2j.parseString('<div>'+consult+'</div>')
      writeFile('./log/' + new Date().toLocaleDateString() + '-' + new Date().getHours() + '-' + new Date().getMinutes() + '-' + new Date().getSeconds() + '-res.txt', content.toString())
      //content = hexToDec(content)
      //console.log( typeof (content))
      content = JSON.parse(content)
      //res.header('content-type', 'text/html; charset=utf8')
      res.send( content )
    })
  }).on('error', function(e){
    console.log("Request Error: " + e.message)
  })
  //req.write('\n')
  console.log(req.output + '\n')
  req.end()
})


app.listen(8002)
function writeFile(file, str){
  // 测试用的中文
  //var str = "\r\n我是一个人Hello myself!";
  // 把中文转换成字节数组
  var arr = iconv.encode(str, 'utf-8')
  // appendFile，如果文件不存在，会自动创建新文件
  // 如果用writeFile，那么会删除旧文件，直接写新文件
  fs.appendFile(file, arr, function(err){
    if (err)
      console.log("fail " + err)
    //else
    //console.log("写入文件ok");
  })
}
var decToHex = function(str){
  var res = []
  for (var i = 0; i < str.length; i++)
    res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4)
  return "\\u" + res.join("\\u")
}
var hexToDec = function(str){
  str = str.replace(/\\/g, "%")
  return unescape(str)
}
